/* 
 * ---------------------------------------------------------------
 * This is the pooling class to avoid creating new instances of a
 * class frequently, or in other words, to reuse resources.
 * 2011, by Wu Mu Xian
 * ---------------------------------------------------------------
*/

package mygame.basicgameframework;

import java.util.ArrayList;
import java.util.List;

// This is a generic class, T can be any type
public class Pool<T> {
	// This is a generic interface, T can be any type
	public interface PoolObjectFactory<T> {
		public T createObject(); // create the object
	}
	
	private final List<T> freeObjects; // the list that stores the freed objects
	// the instance of the pool object factory
	private final PoolObjectFactory<T> factory; 
	private final int maxSize; // the maximum size of the objects
	
	// the constructor
	public Pool(PoolObjectFactory<T> factory, int maxSize) { 
        this.factory = factory; 
        this.maxSize = maxSize; 
        this.freeObjects = new ArrayList<T>(maxSize); 
    }
	
	// create a new object
	public T newObject() { 
        T object = null; 
 
        if (freeObjects.size() == 0) 
            object = factory.createObject(); 
        else 
            object = freeObjects.remove(freeObjects.size() - 1); 
 
        return object; 
    } 
	
	// free a unused object
	public void free(T object) { 
        if (freeObjects.size() < maxSize) 
            freeObjects.add(object); 
    }
}
